var express = require('express');
var router = express.Router();

//导入moment
const moment = require('moment');
const BooklistModel = require('../../models/BooklistModel');

//导入中间件检测登录
const checkLoginMiddleware = require('../../middlewares/checkLoginMiddleware');

//格式化日期对象
// console.log(moment(new Date()).format('YYYY-MM-DD'));

//添加首页的路由规则
router.get('/', (req, res) => {
  //重定向网页 /booklist
  res.redirect('/booklist');
})

/* 图书列表 */
router.get('/booklist', checkLoginMiddleware, function(req, res, next) {

  //读取集合信息
  BooklistModel.find().sort({time: -1}).exec((err, data) => {
    if(err){
      res.status(500).send('读取失败~~~');
      return;
    }
    //响应成功的提示
    res.render('list', {booklists: data, moment: moment});
  })

});

/* chakan图书列表 */
router.get('/booklist/search', checkLoginMiddleware, function(req, res, next) {

  //读取集合信息
  BooklistModel.find({}).sort({type:1}).exec((err, data) => {
    if(err){
      res.status(500).send('读取失败~~~');
      return;
    }
    //响应成功的提示
    res.render('search', {booklists: data, moment: moment});
  })

});

//查改列表
router.get('/booklist/search/:id', checkLoginMiddleware, function(req, res, next) {
  let id = req.params.id;
  //读取集合信息
  BooklistModel.findOne({_id: id}, (err, data) => {
    if(err) {
      res.status(500).send('查看失败~');
      return;
    }
    //响应成功的提示
    res.render('set', {booklists: data, moment: moment});
  })

});

//修改列表
router.post('/booklist/set/:id', checkLoginMiddleware, function(req, res, next) {
  let id = req.params.id;
  //读取集合信息
  BooklistModel.updateOne({_id: id}, {title:req.body.title,
    time:req.body.time,
    type:req.body.type,
    account:req.body.account,
    remarks:req.body.remarks
},(err, data) => {
    if(err) {
      res.status(500).send('修改失败~');
      return;
    }
    res.render('success', {msg: '修改成功了哦~~~', url: '/booklist'});
  })

});



//添加记录
router.get('/booklist/create', checkLoginMiddleware, function(req, res, next) {
  res.render('create');
});

//新增记录
router.post('/booklist', checkLoginMiddleware, function(req, res, next) {
  //获取请求体数据
  // console.log(req.body);

  //插入数据库

  BooklistModel.create({
    ...req.body,
    //修改 time 属性的值
    time: moment(req.body.time).toDate()
  }, (err, data) => {
    if(err){
      res.status(500).send('插入失败~~');
      return;
    }
    
    //成功提醒
    res.render('success', {msg: '添加成功了哦~~~', url: '/booklist'});
  })
  
});

//删除记录
router.get('/booklist/:id', checkLoginMiddleware, (req,res) =>{
  let id = req.params.id;

  //删除
  BooklistModel.deleteOne({_id: id}, (err, data) => {
    if(err) {
      res.status(500).send('删除失败~');
      return;
    }
    //提醒
    res.render('success', {msg: '删除成功~~~', url: '/booklist'});
  })
})

module.exports = router;
